package com.study.spmongodb.book.wwj.char21;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/30 11:31
 */
public class ThreadLocalExample {
    public static void main(String[] args) {

        //创建ThreadLocal 实例
        final ThreadLocal<Integer> tlocal = new ThreadLocal<>();

        //创建10个线程
        IntStream.range(0, 10)
                .forEach(i -> new Thread(() -> {
                    try {
                        //每个线程都会设置tlocal
                        tlocal.set(i);
                        System.out.println(Thread.currentThread().getName() + " set i " + tlocal.get());
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println(Thread.currentThread().getName() + " get i " + tlocal.get());

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start());
    }
}
